#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include "sconfig.h"

#define SCONFIG_SEPARATOR_DEFAULT ','

static char _separator = SCONFIG_SEPARATOR_DEFAULT;

int sconfig_set_separtor(char separator)
{
    _separator = separator;
}

char sconfig_get_separtor()
{
    return _separator;
}

int sconfig_bool(const char *str)
{
    if (!str)
        return 0;
    if (!strncmp(str, "true", 4))
        return 1;
    return 0;
}

int sconfig_int(const char *str)
{
    if (!str)
        return 0;
    return atoi(str);
}

int sconfig_write(char *line, const char *str)
{
    char s[2] = {_separator, '\0'};

    if (!line || !str)
        return -1;
    strcat(line, str);
    strcat(line, s);
}

char *sconfig_read(char *line, const char *str, int len)
{
    char *p = line, *s = (char *)str;
    int byte = len;

    if (!line || !str)
        return NULL;
    if (!*line)
        return NULL;
    while (*p)
    {
        if (*p == _separator)
            p++;
        if (len-- > 0)
        {
            *s++ = *p;
        }
        p++;
    }
    s = (char *)str;
    s[byte - len] = '\0';
    return p;
}

int sconfig_writeline(char *line)
{
    char buff[] = {'\n', '\0'};
    if (!line)
        return -1;
    strcat(line, buff);
}

//read a line and point next line
char *sconfig_read_line(char *buff, const char *line, int len)
{
    char *p = buff;
    char *q = (char *)line;
    int bytes = len;

    if (!buff || !line || len <= 0)
        return NULL;
    if (!buff)
        return NULL;
    while (*p)
    {
        if (*p == '\r') // '\r\n'
            p++;
        if (*p == '\n') // '\r'
        {
            p++;
            break;
        }
        else
            break;
        if (*p == 'r') // '\r'
        {
            p++;
            break;
        }
        if (len > 0)
        {
            *q++ = *p;
            len--;
        }
        p++;
    }
    q = (char *)line;
    q[bytes - len] = '\0';
    return p;
}

char* sconfig_trim(const char *str)
{
    char *start, *end;
    int len = strlen(str);

    if (!str)
        return NULL;
    while (*start && isspace(*start))
        start++; //cut start space
    while (*end && isspace(*end))
        *end-- = '\0'; //cut end space use '\0' to full
    len = strlen(start);
    strcpy(start, str);
    start = (char *)str;
    start[len] = '\0';
    return start;
}